package com.smartens.boit;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.smartens.boit.activity.viewmodel.MainActivityViewMode;
import com.smartens.boit.adapter.mainAdapter;
import com.smartens.boit.base.BaseActivity;

import com.smartens.boit.bean.DeviceListData;
import com.smartens.boit.bean.DevicesList;
import com.smartens.boit.bean.ElectricBean;
import com.smartens.boit.bean.RecordeDetail_datd;
import com.smartens.boit.fragment.FirstFragment;
import com.smartens.boit.fragment.FourthFragment;
import com.smartens.boit.fragment.SecondFragment;
import com.smartens.boit.fragment.ThirdFragment;
import com.smartens.boit.util.AppManager;
import com.smartens.boit.util.HttpHelper;
import com.smartens.boit.util.Util;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import kotlin.Function;

/**
 * @Description 主页
 * @Author songtt
 * @Date 2021/3/4
 */
public class MainActivity extends BaseActivity {
    private ViewPager mViewPager;
    private RadioGroup mTabRadioGroup;
    private int[] rbs = {R.id.rb_equipment, R.id.rb_fault, R.id.rb_energy, R.id.rb_my};
    private List<Fragment> mFragments;
    private FragmentPagerAdapter mAdapter;
    private FirstFragment firstFragment;
    private SecondFragment secondFragment;
    private ThirdFragment thirdFragment;
    private FourthFragment fourthFragment;
    private RadioButton radioButton;
    private TextView redText;
    private HttpHelper helper;
    private ScheduledExecutorService mUpdateTime;
    private TimerTask mUpdateTask;
    private String oldElectric1 = "0.050";
    private String newElectric1 = "0";
    private Boolean isMore = true;
    //private String date;
    private NotificationManager manager;
    private Notification notification;
    private static final float standard = (float) 0.075;

    private static final String TAG = "MainActivity";
    Myservice myservice;
    ServiceConnection serviceConnection;
    private volatile boolean canerror = true;

    Handler handler = new Handler();
    private Thread thread;
    private MyApplication2 application2;
    private AlertDialog alertDialog;
    private int oflineCount;
    private int onlinCount;
    private int faultCount;
    private Thread thread2;
    private boolean stop;
    private MainActivityViewMode mainViewMode;

    private void startService() {
        Intent intent = new Intent(this, Myservice.class);
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myservice = ((Myservice.MyBinder) service).getMyservice();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        stop = false;
        application2 = (MyApplication2) getApplication();
        mViewPager = findViewById(R.id.fragment_vp);
        mTabRadioGroup = findViewById(R.id.tabs_rg);
        radioButton = findViewById(R.id.rb_equipment);
        redText = findViewById(R.id.red_text);
        radioButton.setChecked(true);
        mFragments = new ArrayList<>();
        firstFragment = new FirstFragment();
        secondFragment = new SecondFragment();
        thirdFragment = new ThirdFragment();
        fourthFragment = new FourthFragment();
        mFragments.add(firstFragment);
        mFragments.add(secondFragment);
        mFragments.add(thirdFragment);
        mFragments.add(fourthFragment);
//        // 设置填充器
        mAdapter = new mainAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(4);
        // register listener
        mViewPager.addOnPageChangeListener(mPageChangeListener);
        mTabRadioGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);
        helper = HttpHelper.getInstance();
        //  date = Util.getNowDate();
        startUpdateTimer();
        startService();
        initViewMode();
    }

    private void initViewMode() {
        mainViewMode = MainActivityViewMode.getViewMode(this, getApplication());
        mainViewMode.getIsnewMessage().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    redText.setVisibility(View.VISIBLE);
                } else {
                    redText.setVisibility(View.GONE);
                }
            }
        });
    }


    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v("生命周期", "activityonDestroy");
        application2.faultCount = 0;
        mViewPager.removeOnPageChangeListener(mPageChangeListener);
        unbindService(serviceConnection);
        stop = true;
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();

    }

    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            RadioButton radioButton = (RadioButton) mTabRadioGroup.getChildAt(position);
            radioButton.setChecked(true);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            for (int i = 0; i < group.getChildCount(); i++) {
                if (group.getChildAt(i).getId() == checkedId) {
                    mViewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    };

    /**
     * 定时刷新
     */
    private void startUpdateTimer() {
        thread = new Thread() {
            @Override
            public void run() {
                super.run();
                while (true) {
/*
               if (iserror)
               {
                   try {
                       sleep(5*60*1000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }*/


                    try {
                        sleep(1000);
                        getFault();
                        sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread2 = new Thread() {

            @Override
            public void run() {
                super.run();
                while (true) {
                    if (stop) {
                        return;
                    }
                    getLinxianNum();
                    try {
                        sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
        thread2.start();
    }

    private void getLinxianNum() {
       /* helper.GetDevicesList(3, new HttpHelper.HttpCallBack<DevicesList>() {
            @Override
            public void onSuccess(List<DevicesList> result) {
                //  Log.v("请求成功", String.valueOf(result.size()));
                int num = result.size();
                firstFragment.setLixiannum(num);

            }

            @Override
            public void onFailure(String message) {
                //  Log.v("1122", message);
            }

        });*/
        helper.GetAllDevicesList(new HttpHelper.HttpCallBackClass<DeviceListData>() {
            @Override
            public void onSuccess(DeviceListData result) {
                //离线
                oflineCount = result.getGetDevicesListResult().getOflineCount();
                //正常
                onlinCount = result.getGetDevicesListResult().getOnlineCount();
                //异常
                faultCount = result.getGetDevicesListResult().getFaultCount();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        firstFragment.setLixiannum(oflineCount);
                        firstFragment.setNormal_n(onlinCount - application2.faultCount);
                        firstFragment.setUnnormal_n(faultCount + application2.faultCount);
                    }
                });


            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    /**
     * 获取故障信息
     * 取最后一条对比
     */
    public void getFault() {
        Log.v("sdsfdsfdsf", canerror + "");
        Log.v("sdasfdsfdsf", secondFragment.isErrorC() + "");
/*        if ( secondFragment.isErrorC())
        {
            iserror=false;

            if (firstFragment.isAdded()) {
                firstFragment.setUnnormal_n(0);
                firstFragment.setNormal_n(1);
            }
        }
        if (iserror)
        {

            return;

        }*/

        helper.GetDeviceGroupList("32FFD7055643373914721851", new HttpHelper.HttpCallBack<RecordeDetail_datd>() {
            @Override
            public void onSuccess(List<RecordeDetail_datd> result) {
                //   Log.v("GetDeviceGroupList", "onSuccess: " );
                int i = 0;
                for (int a = 0; a < result.size(); a++) {
                    RecordeDetail_datd devicegroup = result.get(a);
                    int b = Integer.valueOf(devicegroup.getBrightNess());
                    Log.v("liaaaaaaaa" + "亮度", b + "" + "组名" + devicegroup.getGroupName());
                    if (b == 100) {

                        i = i + 1;
                    }
                }
                Log.v("switch--", i + "");
                switch (i) {

                    case 0:
                        break;
                    case 1:
                        getdevic((v) -> {
                            if (v == 0)
                                return true;
                            return false;
                        });
                        break;
                    case 2:

                        getdevic(new Function() {
                            @Override
                            public boolean get(float value) {
                                if (value < 0.06f) {
                                    return true;
                                }
                                return false;
                            }
                        });
                        break;
                }

            }

            @Override
            public void onFailure(String message) {
                //  Log.v("GetDeviceGroupList", "onFailure: " );
            }
        });
    }

    private void getdevic(Function function) {
        helper.GetDeviceStatusHistoryList(Util.getNowDate(), new HttpHelper.HttpCallBack<ElectricBean>() {

            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<ElectricBean> result) {

                //   Log.v("GetDeviceStatusHistoryList", "onSuccess: " );


                if (result.size() > 0) {
                    newElectric1 = result.get(result.size() - 1).getCurrentElectric1();
                    float value = Float.valueOf(newElectric1);
                    Log.v("liaaaaaaaa" + "电流", value + "");
                    if (function.get(value)) {

                        showError(result);


                    } else {
                        canerror = true;
                    }

                }


                Log.i("====getFault onSuccess===", "成功" + isMore);
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                //   Log.v("=====getFault==onFailure", message);
                         /*   iserror=true;
                            showError();*/
            }
        });
    }

    public void settext3() {
        application2.faultCount = 0;
        if (faultCount > 0) {
            firstFragment.setUnnormal_n(faultCount + 1);
        } else {
            firstFragment.setNormal_n(onlinCount - 1);
        }
    }

    interface Function {
        public boolean get(float value);

    }

    private void showError(List<ElectricBean> result) {
        MainActivity.this.runOnUiThread(() -> {
            if (canerror && !application2.isControl) {
                Log.v("sdfdsdfsdfsdf", "ddd");
                                      /*  iserror=true;
                                        handler.postAtTime(()->{iserror=false;},1000*60);*/
                mainViewMode.getIsnewMessage().setValue(true);
                showNormalDialog();
                //   mUpdateTime.shutdownNow();
                application2.faultCount += 1;
                Log.v("异常设备", application2.faultCount + "");
                firstFragment.setNormal_n(onlinCount - application2.faultCount);
                firstFragment.setUnnormal_n(faultCount + application2.faultCount);

                Toast.makeText(MainActivity.this, "设备异常", Toast.LENGTH_LONG).show();
                Intent intent = new Intent();
                intent.putExtra("dateTime", result.get(result.size() - 1).getUpdateTime());
                //对应BroadcastReceiver中intentFilter的action
                intent.setAction("BROADCAST_ACTION");
                //发送广播
                sendBroadcast(intent);
                canerror = false;
            }


        });
    }
/*    public void getFault() {


        helper.GetDeviceStatusHistoryList(date, new HttpHelper.HttpCallBack<ElectricBean>() {

            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<ElectricBean> result) {

                 Log.v("GetDeviceStatusHistoryList", "onSuccess: " );


                if (result.size() > 0) {
                    newElectric1 = result.get(result.size() - 1).getCurrentElectric1();
                    if (Math.abs(Float.parseFloat(newElectric1) - Float.parseFloat(oldElectric1)) > standard) {
                        isMore = true;
                    } else {
                        isMore = false;
                    }
                    oldElectric1 = newElectric1;
                }

                if (isMore) {
                    //提示信息
                    mViewPager.post(new Runnable() {
                        @Override
                        public void run() {
                            showNormalDialog();
                            redText.setVisibility(View.VISIBLE);
                            // Toast.makeText(getApplicationContext(), "有异常" , Toast.LENGTH_LONG).show();
                        }
                    });

                    Intent intent = new Intent();
                    intent.putExtra("dateTime",result.get(result.size() - 1).getUpdateTime());
                    //对应BroadcastReceiver中intentFilter的action
                    intent.setAction("BROADCAST_ACTION");
                    //发送广播
                    sendBroadcast(intent);

                }
                Log.i("====getFault onSuccess===", "成功" + isMore);
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                 Log.v("=====getFault==onFailure", message);
            }
        });
    }*/


    private void showNormalDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
/*        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(AppManager.getAppManager().currentActivity());*/
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("");
        normalDialog.setMessage("当前系统中有设备发生故障，请查看详情");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        alertDialog.dismiss();

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        alertDialog.dismiss();

                    }
                });
        // 显示
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        alertDialog = normalDialog.create();
        if (!isDestroyed())
            alertDialog.show();
    }

/*    public void setRedText() {
        redText.setVisibility(View.GONE);
    }*/

}